import json
import random
from datetime import datetime, time

from django.http import HttpResponse, JsonResponse

from django.shortcuts import render

from django.views.decorators.csrf import csrf_exempt

from wepapi.models import Order
from wepapi.utils.Pagination import Pagination
from wepapi.utils.bootstrap import BootStrapModelForm

datetime.now().strftime('%Y-%m-%d-%H-%M-%S') + str(random.randint(1000, 99999))


class OrderModelForm(BootStrapModelForm):
    class Meta:
        model = Order
        # fields = '__all__'
        exclude = ['oId', 'admin']


def order_list(request):
    queryset = Order.objects.all().order_by('-id')
    page_object = Pagination(request, queryset)
    uform = OrderModelForm()
    context = {'queryset': page_object.page_queryset, 'uform': uform, 'page_string': page_object.html()}
    return render(request, 'order_list.html', context)


@csrf_exempt
def order_add(request):
    """新建订单（AJax请求）"""
    if request.method == 'POST':
        form = OrderModelForm(request.POST)
        if form.is_valid():
            #  订单号：额外增加一些不是用户输入的值（自己拼装的值）
            form.instance.oId = datetime.now().strftime('%Y%m%d%H%M%S') + str(random.randint(1000, 9999))
            # 固定管理员 ID
            form.instance.admin_id = request.session['info']['id']
            # 保存到数据库
            form.save()
            return JsonResponse({'status': True, 'code': 200})
        return JsonResponse({'status': False, 'error': form.errors, 'code': 201})


def order_del(request):
    """删除订单"""
    if request.method == 'GET':
        exsits = Order.objects.filter(id=request.GET['id']).exists()
        if not exsits:
            return JsonResponse({'status': False, 'error': '删除失败', 'code': 201})
        Order.objects.filter(id=request.GET.get('id')).delete()
        return JsonResponse({'status': True, 'code': 200})


def order_details(request):
    """根据ID获取订单详情"""
    """"方式一

        if request.method == 'GET':
            row_object = Order.objects.filter(id=request.GET['id']).first()
            if not row_object:
                return JsonResponse({'status': False, 'error': '数据不存在', 'code': 201})
    
            # 从数据库中获取到一个对象 row_object
            result = {
                'status': True,
                'data': {
                    'id': row_object.id,
                    'oId': row_object.oId,
                    'admin_id': row_object.admin_id,
                    'title': row_object.title,
                    'price': row_object.price,
                    'status': row_object.status,
                },
                'code': 200
            }
    
            return JsonResponse(result)
     """

    """方式二"""
    row_dict = (Order.objects.filter(id=request.GET['id'])
                .values('oId', 'title', 'price', 'status')
                .first())
    if not row_dict:
        return JsonResponse({'status': False, 'error': '数据不存在', 'code': 201})
    # 从数据库中获取到一个对象 row_object
    result = {
        'status': True,
        'data': row_dict,
        'code': 200
    }

    return JsonResponse(result)


@csrf_exempt
def order_edit(request):
    """编辑订单"""
    row_object = Order.objects.filter(id=request.GET['id']).first()
    if not row_object:
        return JsonResponse({'status': False, 'tips': '编辑失败，数据不存在', 'code': 201})

    form = OrderModelForm(request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return JsonResponse({'status': True, 'code': 200})

